package com.examples.springboot.jpa.gui.climbers;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.AbstractCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;

import org.modelmapper.internal.util.Iterables;

import com.examples.springboot.jpa.pojos.MountVo;
import com.examples.springboot.jpa.resources.MountService;

/**
 * A custom editor for cells in the Mount column.
 *
 */
@SuppressWarnings("serial")
public class MountCellEditor extends AbstractCellEditor 
		implements TableCellEditor, ActionListener {

	private MountVo mount;
	private Iterable<MountVo> mounts;
	private final PropertyChangeListener listener;
	private int mSelectRowNumber;

	public MountCellEditor(Iterable<MountVo> mounts,PropertyChangeListener listener) {
		this.listener=listener;
		this.mounts=mounts;
	}

	@Override
	public Object getCellEditorValue() {
	  System.out.println(mount);
		return this.mount;
	}

//	public void loadData() {
//	  setData(mResource.getAll()
//	  );
//  }

	public void setData(Iterable<MountVo> mounts) {
	  this.mounts=mounts;
	  System.out.println("mounts size="+mounts.spliterator().estimateSize());
  }

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value,
			boolean isSelected, int row, int column) {
	  System.out.println(value);
	  if (value instanceof MountVo) {
      this.mount = (MountVo) value;
    }

		JComboBox<MountVo> comboMount = new JComboBox<>();

		for (MountVo mount : mounts) {
			comboMount.addItem(mount);
		}

		int indexOf = indexOf(mount);
		System.out.println("indexOf="+indexOf);
		comboMount.setSelectedIndex(indexOf);
		comboMount.addActionListener(this);
		
		if (isSelected) {
		  comboMount.setBackground(table.getSelectionBackground());
    } else {
      comboMount.setBackground(/* table.getSelectionForeground() */Color.WHITE);
    }
		
 		this.mSelectRowNumber=row;
		return comboMount;
	}

	public int getSelectRowNumber() {
    return mSelectRowNumber;
  }

	private int indexOf(MountVo mount) {
    int i = 0;
	  for (MountVo item : mounts) {
	    if(item.equals(mount))
        return i;
      if(item.getName()!=null&&
          item.getName().equals(mount.name))
        return i;
      i++;
    }

    return -1;
  }

	@Override
	@SuppressWarnings("unchecked")
	public void actionPerformed(ActionEvent event) {
    JComboBox<MountVo> comboMount = (JComboBox<MountVo>) event.getSource();
		listener.propertyChange(new PropertyChangeEvent(comboMount, "onComboboxChanged", getCellEditorValue(), comboMount.getSelectedItem()));
		this.mount = (MountVo) comboMount.getSelectedItem();
	}

}
